#include <bits/stdc++.h>
#include <cmath>
using namespace std;
inline int gn() { 
    int k = 0, f = 1;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if(c == '-') f = -1;
    for (; isdigit(c); c = getchar()) k = k * 10 + c - '0';
    return k * f;
}
short mi[701][701][11][11], mx[701][701][11][11], a[701][701], n, m;
int q, sum[701][701];
char op[5];
void init() { 
    for (int k = 1; 1 << k <= n; k++) { 
        for (int i = 0; i < n; i++) { 
            for (int j = 0; j < m; j++) { 
                if (j + (1 << (k - 1)) > m) break;
                mi[i][j][0][k] = min(mi[i][j][0][k - 1], mi[i][j + (1 << (k - 1))][0][k - 1]);
                mx[i][j][0][k] = max(mx[i][j][0][k - 1], mx[i][j + (1 << (k - 1))][0][k - 1]);
            }
        }
    }
    for (int k = 0; 1 << k <= n; k++) { 
        for (int l = 1; 1 << l <= m; l++) { 
            for (int i = 0; i < n; i++) { 
                if (i + (1 << (l - 1)) > n) break;
                for (int j = 0; j < m; j++) { 
                    if (j + (1 << (k - 1)) > m) break;
                    mi[i][j][l][k] = min(mi[i][j][l - 1][k], mi[i + (1 << (l - 1))][j][l - 1][k]);
                    mx[i][j][l][k] = max(mx[i][j][l - 1][k], mx[i + (1 << (l - 1))][j][l - 1][k]);
                }
            }
        }
    }
}
inline int getmax(int a, int b, int c, int d) { 
    int l = log2(c - a + 1), k = log2(d - b + 1);
    return max(max(mx[a][b][l][k], mx[c - (1 << l) + 1][d - (1 << k) + 1][l][k]), max(mx[a][d - ]));
}
inline int getmin(int a, int b, int c, int d) { 
    int l = log2(c - a + 1), k = log2(d - b + 1);
    return min(mi[a][b][l][k], mi[c - (1 << l) + 1][d - (1 << k) + 1][l][k]);
}
int main() { 
    freopen("phalanx.in", "r", stdin);
    freopen("phalanx.out", "w", stdout);
    memset(mi, 0x7f, sizeof(mi));
    n = gn(), m = gn();
    for (int i = 0, t; i < n; i++)
        for (int j = 0; j < m; j++)  { 
            t = gn();
            sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + t;
            mi[i][j][0][0] = mx[i][j][0][0] = a[i][j] = t;
        }
    init();
    q = gn();
    while (q--) { 
        scanf("%s", op);
        int a = gn(), b = gn(), c = gn(), d = gn();
        if (op[1] == 'U')
            cout << sum[c][d] + sum[a - 1][b - 1] - sum[b - 1][c] - sum[a - 1][d] << '\n';
        else if (op[1] == 'A')  
            cout << getmax(a, b, c, d) << '\n';
        else if (op[1] == 'I') 
            cout << getmin(a, b, c, d) << '\n';
    }
}
